﻿using ERPWinFormWork.Produce.ErrorCode;
using ERPWinFormWork.Produce.Produce.Dtos;
using ERPWinFormWork.Sales;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERPWinFormWork.Produce
{
    public partial class cboState : Form
    {
        public bool IsOperationCompletedss { get; internal set; }
        private ApiClient _apiClient;
   

        private int PageIndex { get; set; } = 1;
        private int PageSize { get; set; } = 15;
        private int TotalPages { get; set; } = 1;
        private int TotalSize { get; set; }
        public cboState()
        {
            InitializeComponent();
            // 初始化 API 客户端（替换为你的实际 API 基础地址）
            _apiClient = new ApiClient(AppConfig.ApiBaseUrl);
            GetData();
            LoadcboStatesData();

            dgvWork_recordData.CellFormatting += dgvWork_recordData_CellFormatting; // Add CellFormatting to display state as text
        }

        // Add CellFormatting event handler to format State column
        private void dgvWork_recordData_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dgvWork_recordData.Columns[e.ColumnIndex].Name == "State" && e.Value != null)
            {
                int state = Convert.ToInt32(e.Value);
                switch (state)
                {
                    case 1: e.Value = "未派工"; break;
                    case 2: e.Value = "已下达"; break;
                    case 3: e.Value = "进行中"; break;
                    case 4: e.Value = "未质检"; break;
                    case 5: e.Value = "已质检"; break;
                    default: e.Value = "未知"; break;
                }
            }
        }

        private async void GetData()
        {
            // 获取状态值（1-4），默认为0（表示全部）
            int stateValue = 0;
            if (cboStates.SelectedItem != null && cboStates.SelectedValue != null)
            {
                int.TryParse(cboStates.SelectedValue.ToString(), out stateValue);
            }
            var parameters = new Dictionary<string, string>
                {
                    { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                    { "Task_Name", this.txtTask_Name.Text.Trim()},
                    { "Work_Number", this.txtWork_Number.Text.Trim() },
                    { "Reporting_Staff", this.txtReporting_Staffs.Text.Trim() },
                    { "State", stateValue.ToString()},

                };


            var response = await _apiClient.GetAsync<ApiResponse<List<Work_recordDto>>>(
                    endpoint: "Production_Plan/GetWork_recordHandle",
                    parameters: parameters
                );
            if (response != null && response.code == 200)
            {
                dgvWork_recordData.DataSource = response.pageData;
                TotalPages = response.totalCount;
                TotalSize = Convert.ToInt32(Math.Ceiling(TotalPages * 1.0 / PageSize));
                this.lblcount.Text = TotalSize.ToString();
                AddOperationColumns();

                // 添加序号列作为第一列
                if (dgvWork_recordData.Columns["SerialNo"] == null)
                {
                    DataGridViewTextBoxColumn serialCol = new DataGridViewTextBoxColumn();
                    serialCol.Name = "SerialNo";
                    serialCol.HeaderText = "序号";
                    serialCol.ReadOnly = true;
                    dgvWork_recordData.Columns.Insert(0, serialCol); // 插入为第一列
                }

                // 填充序号（全局索引，正序）
                for (int i = 0; i < dgvWork_recordData.Rows.Count; i++)
                {
                    int serial = (PageIndex - 1) * PageSize + i + 1;
                    dgvWork_recordData.Rows[i].Cells["SerialNo"].Value = serial;
                }

                // 隐藏Id列
                if (dgvWork_recordData.Columns["Id"] != null)
                {
                    dgvWork_recordData.Columns["Id"].Visible = false;
                }
            }

        }

        private void AddOperationColumns()
        {
            string[] columnNames = { "quality_inspection"};
            string[] headerTexts = { "质检"};

            for (int i = 0; i < columnNames.Length; i++)
            {
                if (dgvWork_recordData.Columns[columnNames[i]] == null)
                {
                    var col = new DataGridViewButtonColumn();
                    col.Name = columnNames[i];
                    col.HeaderText = headerTexts[i];
                    col.Text = headerTexts[i];
                    col.UseColumnTextForButtonValue = true;
                    dgvWork_recordData.Columns.Add(col);
                }
            }
        }


        private void LoadcboStatesData()
        {
            // 模拟一个数据源，这里是简单的字符串列表，实际可从数据库等获取
            var stateList = new List<object>()
    {
      
        new { Text = "未质检", Value = 4 },
        new { Text = "已质检", Value = 5 }
    };

            // 清空ComboBox原有项（可选，避免重复添加）
            cboStates.Items.Clear();
            // 设置数据源
            cboStates.DataSource = stateList;
            // 设置显示的文本字段
            cboStates.DisplayMember = "Text";
            // 设置对应的值字段
            cboStates.ValueMember = "Value";
            // 不设置默认选中项
            cboStates.SelectedIndex = -1;
        }


        private void btnPreviousPage_Click(object sender, EventArgs e)
        {
            if (PageIndex > 1)
            {
                PageIndex--;
                txtCurrentPage.Text = PageIndex.ToString();
                GetData();
            }
        }

        private void btnNextpage_Click(object sender, EventArgs e)
        {
            if (PageIndex < TotalSize)
            {
                PageIndex++;
                txtCurrentPage.Text = PageIndex.ToString();
                GetData();
            }
        }




        private async void dgvWork_recordDataClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                Work_recordDto item = dgvWork_recordData.Rows[e.RowIndex].DataBoundItem as Work_recordDto;
                if (item != null)
                {
                    string colName = dgvWork_recordData.Columns[e.ColumnIndex].Name;
                    if (colName == "quality_inspection")
                    {
                        Report_QualityForm form1 = new Report_QualityForm();
                        form1.ShowDialog();
                        if (form1.IsOperationCompletedss)
                        {
                            var data = new { id = item.Id, state = 5 };
                            var response = await _apiClient.PostAsync<object, ApiResponse<string>>("Production_Plan/DispatchworkHandle", data);

                            if (response != null && response.code == 200)
                            {
                                MessageBox.Show("已修改为已质检状态", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                GetData();
                            }
                            else
                            {
                                MessageBox.Show($"修改为已质检状态失败: {response?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                  
                }
            }
        }

        private void btnGetWhere_Click(object sender, EventArgs e)
        {
            GetData();
        }

        private void btnreset_Click(object sender, EventArgs e)
        {
            txtTask_Name.Clear();
            txtWork_Number.Clear();
            txtReporting_Staffs.Clear();
            cboStates.SelectedIndex = -1;
            GetData();
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            var parameters = new Dictionary<string, string>
            {
                    { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                    { "Task_Name", this.txtTask_Name.Text.Trim()},
                    { "Work_Number", this.txtWork_Number.Text.Trim() },
                    { "Reporting_Staff", this.txtReporting_Staffs.Text.Trim() },
                    { "State", int.TryParse(this.cboStates.Text.Trim(), out int stateValue) ? stateValue.ToString() : "0"},
            };

            // Assuming export endpoint is Sales/DiscountExport and returns ApiResponse<string> with file path or message
            byte[] excelBytes = await _apiClient.GetBytesAsync(
            endpoint: "Production_Plan/GetWork_recordExport", // 后端导出接口名（与 [HttpGet("DiscountGetExport")] 匹配）
            parameters: parameters
             );

            using (var saveDialog = new SaveFileDialog())
            {
                saveDialog.Filter = "Excel文件 (*.xlsx)|*.xlsx|所有文件 (*.*)|*.*"; // 只允许保存xlsx格式
                saveDialog.Title = "保存折扣方案导出文件";
                // 默认文件名：与后端一致（带时间戳，避免重复）
                saveDialog.FileName = $"报工记录_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                saveDialog.RestoreDirectory = true; // 打开时默认显示上次保存的路径

                // 若用户选择了保存路径
                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        // 将二进制流写入本地文件（完成保存）
                        System.IO.File.WriteAllBytes(saveDialog.FileName, excelBytes);

                        // 导出成功提示 + 可选打开文件
                        DialogResult openChoice = MessageBox.Show(
                            $"导出成功！\n文件已保存到：\n{saveDialog.FileName}\n是否立即打开文件？",
                            "导出成功",
                            MessageBoxButtons.YesNo,
                            MessageBoxIcon.Information
                        );

                        if (openChoice == DialogResult.Yes)
                        {
                            // 用系统默认程序（如WPS/Office）打开Excel
                            System.Diagnostics.Process.Start(saveDialog.FileName);
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        // 处理“无保存权限”错误（如选择C盘根目录）
                        MessageBox.Show("导出失败：没有文件保存权限！请选择桌面或其他有权限的路径。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    catch (System.IO.IOException ex)
                    {
                        // 处理“文件被占用”错误（如Excel已打开）
                        MessageBox.Show($"导出失败：文件被占用！\n原因：{ex.Message}\n请先关闭已打开的同名Excel文件。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
    }
}
